<template>
  <div class="analysis-container">
    <!-- 筛选栏 -->
    <div class="filter-card">
      <el-select
      filterable
        v-model="query.subId"
        placeholder="请选择课程"
        class="course-select"
        @change="fetchData"
      >
        <el-option
          v-for="(item, index) in courseList"
          :key="index"
          :label="item.subName"
          :value="item.subId"
          class="course-option"
        />
      </el-select>
    </div>

    <!-- 图表容器 -->
    <div class="chart-card">
      <div v-show="!loading && !error" ref="chart" class="chart-wrapper"></div>

      <!-- 加载状态 -->
      <div v-show="loading" class="state-overlay loading-state">
        <i class="el-icon-loading"></i>
        <span class="state-text">数据加载中...</span>
      </div>

      <!-- 错误状态 -->
      <div v-show="error" class="state-overlay error-state">
        <i class="el-icon-warning"></i>
        <span class="state-text">{{ errorMessage }}</span>
        <el-button 
          type="danger" 
          plain 
          size="small"
          @click="fetchData"
          class="retry-btn"
        >
          重试
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getDiff, getSub } from '@/api/txySupervisionEvaluation';

export default {
  data() {
    return {
      scoreData: [],
      query: { subId: '' },
      courseList: [],
      loading: false,
      error: false,
      errorMessage: '',
      chart: null
    };
  },
  mounted() {
    this.initCourse();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chart?.dispose();
  },
  methods: {
    async initCourse() {
      try {
        const res = await getSub();
        this.courseList = res.data;
      } catch (error) {
        this.handleError(error, '课程列表加载失败');
      }
    },
    async fetchData() {
      try {
        this.loading = true;
        this.error = false;
        const res = await getDiff(this.query);
        this.scoreData = res.data.filter(item => item.supervisionScore >= 10);
        this.updateChart();
      } catch (error) {
        this.handleError(error, '数据加载失败');
      } finally {
        this.loading = false;
      }
    },
    updateChart() {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chart);
      }
      
      const option = {
        title: {
          text: '课程评分趋势分析',
          left: 'center',
          textStyle: {
            color: '#2c3e50',
            fontSize: 18,
            fontWeight: '500'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(50,50,50,0.95)',
          borderWidth: 0,
          textStyle: { color: '#fff' },
          formatter: params => {
            const data = params[0];
            return `
              <div style="text-align: left">
                <div style="font-size:14px;margin-bottom:8px">${data.name}</div>
                <div style="display:flex;align-items:center">
                  <span style="display:inline-block;width:8px;height:8px;background:${data.color};border-radius:50%;margin-right:8px"></span>
                  ${data.seriesName}: <strong style="margin-left:8px">${data.value} 分</strong>
                </div>
              </div>
            `;
          }
        },
        xAxis: {
          type: 'category',
          data: this.scoreData.map(item => item.semester),
          axisLabel: {
            rotate: 30,
            color: '#666'
          },
          axisLine: { show: false },
          axisTick: { show: false }
        },
        yAxis: {
          type: 'value',
          name: '评分（分）',
          min: 0,
          max: 100,
          splitLine: {
            lineStyle: { type: 'dashed' }
          },
          axisLabel: { color: '#999' }
        },
        series: [{
          name: '平均分',
          type: 'bar',
          data: this.scoreData.map(item => item.supervisionScore),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#5b8ff9' },
              { offset: 1, color: '#5b8ff9' }
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          emphasis: {
            itemStyle: {
              shadowColor: 'rgba(91,143,249,0.6)',
              shadowBlur: 8
            }
          },
          label: {
            show: true,
            position: 'top',
            color: '#5b8ff9',
            fontWeight: '600'
          }
        }],
        grid: {
          left: '5%',
          right: '5%',
          bottom: '15%',
          containLabel: true
        }
      };

      this.chart.setOption(option);
    },
    handleResize() {
      this.chart?.resize();
    },
    handleError(error, defaultMsg) {
      this.error = true;
      this.errorMessage = error.response?.data?.message || defaultMsg;
    }
  },
  watch: {
    scoreData() {
      this.$nextTick(() => this.updateChart());
    }
  }
};
</script>

<style scoped lang="scss">
.analysis-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  
  .course-select {
    width: 300px;
    
  }
}

.chart-card {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  padding: 20px;
  position: relative;
  min-height: 600px;

  .chart-wrapper {
    width: 1500px;
    height: 600px;
  }
}

.state-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255,255,255,.9);
  border-radius: 4px;
  
  .el-icon {
    font-size: 40px;
    margin-bottom: 12px;
  }

  .state-text {
    color: #606266;
    font-size: 14px;
    margin-bottom: 10px;
  }

  &.loading-state {
    .el-icon-loading {
      color: #409EFF;
      animation: rotating 2s linear infinite;
    }
  }

  &.error-state {
    .el-icon-warning {
      color: #F56C6C;
    }
  }
}

.retry-btn {
  padding: 7px 20px;
  border-radius: 4px;
  transition: all .3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 6px rgba(245,108,108,.3);
  }
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>